package com.abcode.nettyclient.client;

import com.abcode.nettyclient.client.pojo.ChatDto;
import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
@Slf4j
public class NettyClientHandler2 extends SimpleChannelInboundHandler<Object> {
    private final NettyClientConfig config;
     public NettyClientHandler2(NettyClientConfig config) {
        this.config = config;
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    /**
                     *  利用写空闲发送心跳检测消息
                     */
                    ChatDto pingDto=new ChatDto();
                    pingDto.setMsg("我是心跳包");
                    ctx.writeAndFlush(JSON.toJSONString(pingDto));
                    log.info("send ping to server----------");
                    break;
                default:
                    break;
            }
        }
    }

     @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与服务器断开连接，进行重连...");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(() -> {
            try {
                System.out.println("channelInactive schedule reconnect");
                config.reconnect();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 10L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
     @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理消息
        System.out.println("客户端收到消息：" + msg.toString());
    }
     @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端发生异常：" + cause.getMessage());
        ctx.close();
    }
}